package com.qk.management.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.domain.business.BusinessDO;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.entity.Business;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.service.BusinessService;
import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import com.qk.dto.business.BusinessDetailDTO;
import com.qk.entity.BusinessTrackRecord;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import org.springframework.beans.BeanUtils;


@Slf4j
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    
    @Autowired
    private BusinessMapper businessMapper;
    
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public PageResult<BusinessDO> getBusinessList(BusinessListDTO dto) {
        // 计算偏移量
        Integer offset = (dto.getPage() - 1) * dto.getPageSize();
        
        // 查询列表
        List<BusinessDO> businessList = businessMapper.selectBusinessList(dto, offset, dto.getPageSize());
        
        // 查询总数
        Integer total = businessMapper.selectBusinessCount(dto);
        
        // 构造返回结果
        return PageResult.<BusinessDO>builder()
                .total(total)
                .rows(businessList)
                .build();
    }
    
    @Override
    public PageResult<Business> getBusinessPool(BusinessListDTO dto) {
        // 设置默认分页参数
        if (dto.getPage() == null || dto.getPage() <= 0) {
            dto.setPage(1);
        }
        if (dto.getPageSize() == null || dto.getPageSize() <= 0) {
            dto.setPageSize(10);
        }
        
        // 计算偏移量
        Integer offset = (dto.getPage() - 1) * dto.getPageSize();
        
        // 查询公海商机总数
        Integer total = businessMapper.selectBusinessPoolCount(dto);
        
        // 查询公海商机列表
        List<Business> rows = businessMapper.selectBusinessPoolList(dto, offset, dto.getPageSize());
        
        return PageResult.<Business>builder()
                .total(total)
                .rows(rows)
                .build();
    }
    
    @Transactional
    @Override
    public void addBusiness(BusinessDTO businessDTO) {
        // 校验必填字段
        if (ObjectUtil.isEmpty(businessDTO.getPhone()) || ObjectUtil.isEmpty(businessDTO.getName())|| ObjectUtil.isEmpty(businessDTO.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        // 设置创建和更新时间
        Business business = BeanUtil.copyProperties(businessDTO, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        
        // 默认状态为待分配
        if (business.getStatus() == null) {
            business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        }
        
        // 保存商机
        businessMapper.insert(business);
    }
    
    @Transactional
    @Override
    public void assignBusiness(Integer businessId, Integer userId) {
        // 参数校验
        if (ObjectUtil.isEmpty(businessId) || ObjectUtil.isEmpty(userId)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 查询商机是否存在
        Business business = businessMapper.selectBusinessById(businessId);
        if (ObjectUtil.isEmpty(business)) {
            throw new CommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 更新商机信息：分配给指定用户，状态改为待跟进
        business.setUserId(userId);
        business.setStatus(BusinessStatusConstants.WAIT_FOLLOW_UP);
        business.setUpdateTime(LocalDateTime.now());
        
        // 保存更新
        businessMapper.updateById(business);
    }
    
    @Transactional
    @Override
    public void backToPool(Integer id) {
        // 参数校验
        if (ObjectUtil.isEmpty(id)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 查询商机（包含归属人信息）
        Business business = businessMapper.selectBusinessById(id);
        if (ObjectUtil.isEmpty(business)) {
            throw new CommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 更新商机信息：移除用户，状态改回待分配
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setUpdateTime(LocalDateTime.now());
        
        // 保存更新
        businessMapper.updateById(business);
    }
    
    @Transactional
    @Override
    public void toCustomer(Integer id) {
        // 参数校验
        if (ObjectUtil.isEmpty(id)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 查询商机是否存在
        Business business = businessMapper.selectBusinessById(id);
        if (ObjectUtil.isEmpty(business)) {
            throw new CommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 更新商机信息：状态改为已转客户
        business.setStatus(BusinessStatusConstants.CONVERT_TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        
        // 保存更新
        businessMapper.updateById(business);
    }
    
    @Override
    public BusinessDetailDTO getBusinessById(Integer id) {
        // 参数校验
        if (ObjectUtil.isEmpty(id)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 查询商机
        Business business = businessMapper.selectBusinessById(id);
        if (ObjectUtil.isEmpty(business)) {
            throw new CommonException(ParamEnum.PARAM_ERROR);
        }
        
        // 转换为详情DTO
        BusinessDetailDTO detailDTO = new BusinessDetailDTO();
        // 复制商机基本信息
        BeanUtils.copyProperties(business, detailDTO);
        
        // 查询跟进记录（SQL已通过LEFT JOIN获取assignName）
        List<BusinessTrackRecord> trackRecords = businessTrackRecordMapper.selectByBusinessId(id);
        
        // 确保trackRecords不为空时才设置
        if (trackRecords != null) {
            detailDTO.setTrackRecords(trackRecords);
        }
        
        return detailDTO;
    }
    


}